package com.ungs.form;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Font;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;

import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.UIManager;
import javax.swing.border.EmptyBorder;
import javax.swing.border.LineBorder;
import javax.swing.border.TitledBorder;

import com.ungs.readXML.ReadXMLFile;
import com.ungs.utils.CompletarBD;
import com.ungs.utils.Constantes;

public class HibernateConfig extends JDialog {
	private static final long serialVersionUID = 1L;
	private final JPanel contentPanel = new JPanel();
	private JTextField txtHost;
	private JTextField txtEsquema;
	private JTextField txtUser;
	private JTextField txtPass;
	ReadXMLFile file = new ReadXMLFile();
	private JFrame jframe;

	public HibernateConfig() {
		setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
		// Selecciono Look And Feel del sistema
		try {
			UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
		} catch (Exception e) {
			e.printStackTrace();
		}
		crear();

	}

	public HibernateConfig(JFrame parent) {
		jframe = parent;
		// Selecciono Look And Feel del sistema
		try {
			UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
		} catch (Exception e) {
			e.printStackTrace();
		}
		crear();
		cargarForm();
	}

	private void crear() {
		JOptionPane.showMessageDialog(this, "Bienvenido a CMYK, ingrese \n"
				+ "los parametros de la BD.", "Bienvenido a CMYK",
				JOptionPane.INFORMATION_MESSAGE);
		setTitle("Configuracion BD");
		setBounds(100, 100, 450, 284);
		getContentPane().setLayout(new BorderLayout());
		contentPanel.setBackground(Color.WHITE);
		contentPanel.setBorder(new EmptyBorder(5, 5, 5, 5));
		getContentPane().add(contentPanel, BorderLayout.CENTER);
		contentPanel.setLayout(null);
		{
			JPanel panel = new JPanel();
			panel.setBackground(Color.WHITE);
			panel.setLayout(null);
			panel.setBorder(new TitledBorder(
					new LineBorder(new Color(0, 0, 0)), " Parametros ",
					TitledBorder.LEADING, TitledBorder.TOP, null, new Color(0,
							0, 0)));
			panel.setBounds(10, 11, 414, 195);
			contentPanel.add(panel);
			{
				JLabel label = new JLabel("host:puerto");
				label.setFont(new Font("Tahoma", Font.BOLD | Font.ITALIC, 11));
				label.setBounds(48, 35, 86, 14);
				panel.add(label);
			}
			{
				txtHost = new JTextField();
				txtHost.setText("localhost:3306");
				txtHost.setColumns(10);
				txtHost.setBounds(136, 32, 200, 20);
				panel.add(txtHost);
			}
			{
				JLabel label = new JLabel("Esquema");
				label.setFont(new Font("Tahoma", Font.BOLD | Font.ITALIC, 11));
				label.setBounds(48, 72, 86, 14);
				panel.add(label);
			}
			{
				txtEsquema = new JTextField();
				txtEsquema.setText("imprenta");
				txtEsquema.setColumns(10);
				txtEsquema.setBounds(136, 69, 200, 20);
				panel.add(txtEsquema);
			}
			{
				JLabel label = new JLabel("User");
				label.setFont(new Font("Tahoma", Font.BOLD | Font.ITALIC, 11));
				label.setBounds(48, 108, 86, 14);
				panel.add(label);
			}
			{
				txtUser = new JTextField();
				txtUser.setText("root");
				txtUser.setColumns(10);
				txtUser.setBounds(136, 105, 200, 20);
				panel.add(txtUser);
			}
			{
				JLabel label = new JLabel("Pass");
				label.setFont(new Font("Tahoma", Font.BOLD | Font.ITALIC, 11));
				label.setBounds(48, 142, 86, 14);
				panel.add(label);
			}
			{
				txtPass = new JTextField();
				txtPass.setText("root");
				txtPass.setColumns(10);
				txtPass.setBounds(136, 139, 200, 20);
				panel.add(txtPass);
			}
		}
		{
			JButton button = new JButton("Aceptar");
			button.setBackground(Color.WHITE);
			button.addMouseListener(new MouseAdapter() {
				@Override
				public void mouseClicked(MouseEvent arg0) {
					eventoBotonAceptar();
				}
			});
			button.setBounds(236, 217, 89, 23);
			contentPanel.add(button);
		}

		JButton btnSalir = new JButton("Salir");
		btnSalir.setBackground(Color.WHITE);
		btnSalir.addMouseListener(new MouseAdapter() {
			@Override
			public void mouseClicked(MouseEvent arg0) {
				eventoBotonSalir();
			}
		});
		btnSalir.setBounds(335, 217, 89, 23);
		contentPanel.add(btnSalir);
	}

	private void cargarForm() {
		txtHost.setText(file.getHost());
		txtEsquema.setText(file.getEsquema());
		txtPass.setText(file.getPass());
		txtUser.setText(file.getUser());
	}

	private void eventoBotonAceptar() {
		if (file.getEsquema().equals(txtEsquema.getText())
				&& file.getHost().equals(txtHost.getText())
				&& file.getUser().equals(txtUser.getText())
				&& file.getPass().equals(txtPass.getText())) {
			this.dispose();
		} else {
			cargarDatosBDConfIni();

			if (jframe != null) {
				// Si se abre desde el menu dePrincipalForm
				jframe.dispose();
				file.changeModificado(true);

				file.createHibernateCFG(txtHost.getText(),
						txtEsquema.getText(), txtUser.getText(),
						txtPass.getText(), Constantes.CREATE);

				JOptionPane
						.showMessageDialog(
								this,
								"Se acaba de modificar la configuracion,\n"
										+ "la aplicacion se cerrara. \n Los cambios se aplicaran en el proximo inicio.",
								"", JOptionPane.INFORMATION_MESSAGE);
				System.exit(0);

			} else {
				// Si se abre por primera vez la aplicacion
				file.createHibernateCFG(txtHost.getText(),
						txtEsquema.getText(), txtUser.getText(),
						txtPass.getText(), Constantes.CREATE);

				file.createHibernateCFG(txtHost.getText(),
						txtEsquema.getText(), txtUser.getText(),
						txtPass.getText(), Constantes.UPDATE);

				file.changeFirstRun(false);
				CompletarBD.guardar();
				PrincipalForm form = new PrincipalForm();
				this.dispose();
				form.setVisible(true);
			}

		}
	}

	private void eventoBotonSalir() {
		this.dispose();
	}

	@SuppressWarnings("unused")
	private void borrarTablas() {
		// logger.debug("Borrando tablas");

		/*
		 * ConexionBD connection; connection = new ConexionBD(); String database
		 * = txtEsquema.getText().trim(); try {
		 * 
		 * String queryDropTable = "DROP table " + database +
		 * ".detalle_compra, " + database + ".detalle_stock, " + database +
		 * ".incidente, " + database + ".proceso_por_orden, " + database +
		 * ".material, " + database + ".stock_material, " + database +
		 * ".solicitud_compra, " + database + ".condicion_entrega, " + database
		 * + ".orden_trabajo, " + database + ".cliente, " + database +
		 * ".calidad, " + database + ".variante, " + database +
		 * ".formato_papel, " + database + ".proveedor, " + database +
		 * ".persona, " + database + ".direccion, " + database + ".proceso;";
		 * 
		 * 
		 * 
		 * 
		 * 
		 * Statement dropDatabase = connection.getConnection()
		 * .createStatement(); System.out.println(">>SQL: " + queryDropTable);
		 * dropDatabase.execute(queryDropTable); dropDatabase.close();
		 * 
		 * } catch (SQLException sqlEx) { System.err.println(sqlEx + "Table"); }
		 * catch (NullPointerException nullP) { System.err.println(nullP); }
		 * finally { connection.desconectar(); }
		 */
	}

	private void cargarDatosBDConfIni() {
		ReadXMLFile file = new ReadXMLFile();
		file.setEsquema(txtEsquema.getText());
		file.setUser(txtUser.getText());
		file.setPass(txtPass.getText());
		file.setHost(txtHost.getText());
	}

}
